CHECK = require './_create_check'
ERROR = require "./_error.coffee"
PG = require('fckoa/db/pg')
USER = require './_model/user'
R = require './_r'
session = require './_session'
{CACHE} = require('fckoa/db/redis')
KEY = require './_verify_key'


_create = (column)->
    (ctx)->
        body = ctx.request.body
        {key, password, name} = body
        name = name.trim()
        key = R.new[column]+key
        val = await CACHE.get(key)
        if not val
            raise val:""

        err = {
            password:CHECK.password(password)
            name:CHECK.name(name)
        }
        raise err

        table = 'auth.user'
        PG.transaction (trx) ->
            val_id = await trx.val_id('auth.'+column, val)
            user_table = "auth.user_"+column
            if await trx.select_val_id(
                user_table
                val_id
            )
                raise val:false

            if await trx.select_val_id(table, name)
                err.name = ERROR.NAME.EXIST

            raise err

            user_id = await trx.val_id(table, name)

            await trx.set(user_table, user_id, val_id)

            await USER.password(
                user_id
                password
                trx
            )
            await CACHE.del(key)

            await session.bind(user_id, ctx.header.i)
            ctx.body = 0


module.exports = require('fckoa/router') {
get:{
":en(mail|phone)-:key":(ctx)->
    {key, en} = ctx.params
    cache = KEY[en]
    val = await cache.get(key)
    if val
        if await USER["id_by_"+en](val)
            await cache.del(key)
            ctx.body = false
            return

        await cache.renew(key)

    ctx.body = val or ''
}
post:{
phone:(ctx)->
    ctx.body = 0

mail:_create('mail')
phone:_create('phone')
}
}

